/**
 * 错词本管理
 */

class WrongbookManager {
    constructor() {
        this.wrongWords = {};
        this.sortBy = 'recent'; // recent, count, alpha
        this.filterCategory = 'all';
        this.searchKeyword = '';
        
        this.loadWrongWords();
        
        console.log('📕 错词本管理器已加载');
    }

    /**
     * 加载错词数据
     */
    loadWrongWords() {
        this.wrongWords = storageManager.get(storageManager.keys.WRONG_WORDS) || {};
    }

    /**
     * 获取错词数量
     */
    getWrongWordsCount() {
        return Object.keys(this.wrongWords).length;
    }

    /**
     * 添加错词
     */
    addWrongWord(word, userInput, mode) {
        console.log('添加错词:', word);
        
        if (!this.wrongWords[word]) {
            // 获取单词的详细信息
            const wordInfo = this.getWordInfo(word);
            
            this.wrongWords[word] = {
                word: word,
                translation: wordInfo.translation || '',
                category: wordInfo.category || '',
                wordbookId: wordInfo.wordbookId || '',
                wordbookName: wordInfo.wordbookName || '',
                wrongCount: 0,
                correctCount: 0,
                accuracy: 0,
                firstWrong: new Date().toISOString(),
                lastWrong: null,
                wrongHistory: []
            };
        }

        const data = this.wrongWords[word];
        data.wrongCount++;
        data.lastWrong = new Date().toISOString();
        
        // 记录错误历史
        data.wrongHistory.push({
            date: new Date().toISOString(),
            userInput: userInput,
            mode: mode
        });

        // 更新正确率
        const total = data.wrongCount + data.correctCount;
        data.accuracy = total > 0 ? data.correctCount / total : 0;

        this.saveWrongWords();
        this.updateBadge();
    }

    /**
     * 获取单词详细信息
     */
    getWordInfo(word) {
        if (!window.wordbookManager) return {};

        const wordbooks = wordbookManager.getAllWordbooks();
        for (const wb of wordbooks) {
            const wordData = wb.words.find(w => w.word === word);
            if (wordData) {
                return {
                    ...wordData,
                    wordbookId: wb.id,
                    wordbookName: wb.name
                };
            }
        }
        return {};
    }

    /**
     * 移除错词
     */
    removeWrongWord(word) {
        if (this.wrongWords[word]) {
            delete this.wrongWords[word];
            this.saveWrongWords();
            this.updateBadge();
            this.render();
        }
    }

    /**
     * 清空错词本
     */
    clearWrongbook() {
        if (confirm('确定要清空所有错词吗？此操作不可恢复！')) {
            this.wrongWords = {};
            this.saveWrongWords();
            this.updateBadge();
            this.render();
            alert('错词本已清空');
        }
    }

    /**
     * 保存错词
     */
    saveWrongWords() {
        storageManager.set(storageManager.keys.WRONG_WORDS, this.wrongWords);
    }

    /**
     * 更新徽章
     */
    updateBadge() {
        const count = this.getWrongWordsCount();
        const badges = document.querySelectorAll('#wrongbook-count');
        badges.forEach(badge => {
            badge.textContent = count;
            badge.style.display = count > 0 ? 'inline-block' : 'none';
        });

        // 更新首页
        const homeCount = document.getElementById('wrongbook-count-home');
        if (homeCount) {
            homeCount.textContent = count;
        }
    }

    /**
     * 渲染错词本页面
     */
    render() {
        console.log('渲染错词本页面');
        
        this.loadWrongWords();
        this.renderHeader();
        this.renderControls();
        this.renderWrongWordsList();
        this.bindEvents();
    }

    /**
     * 渲染头部
     */
    renderHeader() {
        const count = this.getWrongWordsCount();
        
        const reviewBtn = document.getElementById('btn-review-all-wrong');
        const clearBtn = document.getElementById('btn-clear-wrongbook');
        
        if (reviewBtn) {
            reviewBtn.disabled = count === 0;
            reviewBtn.textContent = count > 0 ? `复习所有错词 (${count})` : '暂无错词';
        }
        
        if (clearBtn) {
            clearBtn.disabled = count === 0;
        }
    }

    /**
     * 渲染控件
     */
    renderControls() {
        // 提取所有分类
        const categories = [...new Set(
            Object.values(this.wrongWords)
                .map(w => w.category)
                .filter(c => c)
        )];

        const filterSelect = document.getElementById('wrongbook-filter');
        if (filterSelect && categories.length > 0) {
            filterSelect.innerHTML = '<option value="all">全部分类</option>' +
                categories.map(c => `<option value="${c}">${c}</option>`).join('');
        }
    }

    /**
     * 渲染错词列表
     */
    renderWrongWordsList() {
        const container = document.getElementById('wrong-words-list');
        if (!container) return;

        const words = this.getFilteredWords();

        if (words.length === 0) {
            container.innerHTML = `
                <div class="empty-state">
                    <div class="empty-state-icon">🎉</div>
                    <h3>太棒了！暂无错词</h3>
                    <p>继续保持，加油学习！</p>
                </div>
            `;
            return;
        }

        container.innerHTML = words.map(word => this.renderWrongWordItem(word)).join('');
    }

    /**
     * 获取筛选后的错词
     */
    getFilteredWords() {
        let words = Object.values(this.wrongWords);

        // 搜索
        if (this.searchKeyword) {
            const keyword = this.searchKeyword.toLowerCase();
            words = words.filter(w => 
                w.word.toLowerCase().includes(keyword) ||
                w.translation?.toLowerCase().includes(keyword)
            );
        }

        // 分类筛选
        if (this.filterCategory !== 'all') {
            words = words.filter(w => w.category === this.filterCategory);
        }

        // 排序
        words.sort((a, b) => {
            switch(this.sortBy) {
                case 'recent':
                    return new Date(b.lastWrong) - new Date(a.lastWrong);
                case 'count':
                    return b.wrongCount - a.wrongCount;
                case 'alpha':
                    return a.word.localeCompare(b.word);
                default:
                    return 0;
            }
        });

        return words;
    }

    /**
     * 渲染错词项
     */
    renderWrongWordItem(wordData) {
        const displayWord = wordData.word.includes(' ') 
            ? this.formatCamelCase(wordData.word)
            : wordData.word;

        return `
            <div class="wrong-word-item">
                <div class="wrong-word-header">
                    <div class="wrong-word-main">
                        <code class="wrong-word-text">${displayWord}</code>
                        <span class="wrong-word-translation">${wordData.translation || '无释义'}</span>
                    </div>
                    <div class="wrong-word-actions">
                        <button class="btn-icon-small" onclick="wrongbookManager.playWord('${wordData.word.replace(/'/g, "\\'")}')">
                            🔊
                        </button>
                        <button class="btn btn-sm btn-secondary" onclick="wrongbookManager.practiceWord('${wordData.word.replace(/'/g, "\\'")}')">
                            练习
                        </button>
                        <button class="btn btn-sm btn-danger" onclick="wrongbookManager.removeWrongWord('${wordData.word.replace(/'/g, "\\'")}')">
                            移除
                        </button>
                    </div>
                </div>
                
                <div class="wrong-word-stats">
                    <span class="stat-tag stat-error">❌ 错误 ${wordData.wrongCount} 次</span>
                    ${wordData.correctCount > 0 ? `<span class="stat-tag stat-success">✅ 正确 ${wordData.correctCount} 次</span>` : ''}
                    <span class="stat-tag">📊 正确率 ${Math.round(wordData.accuracy * 100)}%</span>
                    <span class="stat-tag">🕐 ${this.formatDate(wordData.lastWrong)}</span>
                    ${wordData.category ? `<span class="stat-tag">🏷️ ${wordData.category}</span>` : ''}
                </div>

                ${wordData.wrongHistory && wordData.wrongHistory.length > 0 ? `
                    <div class="wrong-history-preview">
                        <div class="history-item-small">
                            最近错误: ${wordData.wrongHistory[wordData.wrongHistory.length - 1].userInput || '(空)'}
                        </div>
                    </div>
                ` : ''}
            </div>
        `;
    }

    /**
     * 格式化为驼峰
     */
    formatCamelCase(word) {
        if (word.includes(' ')) {
            const words = word.split(' ');
            return words[0].toLowerCase() + 
                   words.slice(1).map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join('');
        }
        return word;
    }

    /**
     * 格式化日期
     */
    formatDate(dateString) {
        if (!dateString) return '未知';
        
        const date = new Date(dateString);
        const now = new Date();
        const diffMs = now - date;
        const diffMins = Math.floor(diffMs / (1000 * 60));
        const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
        const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

        if (diffMins < 1) return '刚刚';
        if (diffMins < 60) return `${diffMins}分钟前`;
        if (diffHours < 24) return `${diffHours}小时前`;
        if (diffDays === 0) return '今天';
        if (diffDays === 1) return '昨天';
        if (diffDays < 7) return `${diffDays}天前`;
        return date.toLocaleDateString();
    }

    /**
     * 播放单词
     */
    playWord(word) {
        if (!window.speechManager) return;

        // 从错词数据中获取播放模式
        const wordData = this.wrongWords[word];
        if (!wordData) return;

        // 判断是否需要分词播放
        if (word.includes(' ')) {
            const displayWord = this.formatCamelCase(word);
            speechManager.speakCamelCase(displayWord);
        } else {
            speechManager.speak(word);
        }
    }

    /**
     * 练习单个错词
     */
    practiceWord(word) {
        // 获取单词数据
        const wordData = this.wrongWords[word];
        if (!wordData) return;

        // 从单词本中找到完整单词数据
        const fullWordData = this.getWordInfo(word);
        if (!fullWordData.word) {
            alert('无法找到单词数据');
            return;
        }

        // 启动听写模式（单个单词）
        if (window.dictationManager) {
            if (window.app) {
                app.navigateTo('dictation');
            }
            dictationManager.start([fullWordData], 'camelCase');
        }
    }

    /**
     * 复习所有错词
     */
    reviewAllWrong() {
        const words = this.getFilteredWords();
        
        if (words.length === 0) {
            alert('没有错词需要复习');
            return;
        }

        // 获取完整单词数据
        const fullWords = words.map(w => this.getWordInfo(w.word)).filter(w => w.word);

        if (fullWords.length === 0) {
            alert('无法加载错词数据');
            return;
        }

        // 启动听写模式
        if (window.dictationManager) {
            if (window.app) {
                app.navigateTo('dictation');
            }
            dictationManager.start(fullWords, 'camelCase');
        }
    }

    /**
     * 绑定事件
     */
    bindEvents() {
        // 搜索
        const searchInput = document.getElementById('search-wrong-words');
        if (searchInput) {
            searchInput.addEventListener('input', (e) => {
                this.searchKeyword = e.target.value;
                this.renderWrongWordsList();
            });
        }

        // 排序
        const sortSelect = document.getElementById('wrongbook-sort');
        if (sortSelect) {
            sortSelect.addEventListener('change', (e) => {
                this.sortBy = e.target.value;
                this.renderWrongWordsList();
            });
        }

        // 筛选
        const filterSelect = document.getElementById('wrongbook-filter');
        if (filterSelect) {
            filterSelect.addEventListener('change', (e) => {
                this.filterCategory = e.target.value;
                this.renderWrongWordsList();
            });
        }

        // 复习所有错词
        const reviewAllBtn = document.getElementById('btn-review-all-wrong');
        if (reviewAllBtn) {
            reviewAllBtn.addEventListener('click', () => {
                this.reviewAllWrong();
            });
        }

        // 清空错词本
        const clearBtn = document.getElementById('btn-clear-wrongbook');
        if (clearBtn) {
            clearBtn.addEventListener('click', () => {
                this.clearWrongbook();
            });
        }
    }
}

// 全局实例
const wrongbookManager = new WrongbookManager();
window.wrongbookManager = wrongbookManager;
